package com.ma4567.remotecontroller.VideoRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import com.ma4567.remotecontroller.util.NginxController;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

class VideoSourceResponse extends com.ma4567.remotecontroller.util.CustomRespone{
    public String url;

    public VideoSourceResponse(int status, String url) {
        super(status);
        this.url = url;
    }
}

@CrossOrigin
@RestController
public class VideoSourceRequest {
    @RequestMapping(value = "/api/getVideoStream", method = RequestMethod.GET)
    public String getVideoStream(HttpServletRequest request,
                                 @RequestParam("cookie") String Cookie) throws SQLException {
        TableRequestLog.AddLog("Request stream", Cookie, request.getRemoteAddr());

        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴cookie
            return JSONObject.toJSONString(new VideoSourceResponse(1, null), SerializerFeature.PrettyFormat);
        }
        else {
            if(!RemoteControllerApplication.userManager.GetUserSingleItemPermission(Cookie, "RemoteControl")){//鉴权
                return JSONObject.toJSONString(new VideoSourceResponse(2, null), SerializerFeature.PrettyFormat);
            }
            else {
                Thread NginxThread = new Thread(new NginxController());
                NginxThread.start();

                Thread ffmpegThread = new Thread(new ffmpegController());
                ffmpegThread.start();
                TableLogManager.AddLog("Request stream", Cookie);
                return JSONObject.toJSONString(new VideoSourceResponse(0, "http://192.168.137.1:80/flv?port=1935&app=live&stream=live"), SerializerFeature.PrettyFormat);
            }
        }
    }
}
